package kamikaze.service.product;

import javax.persistence.Query;

import kamikaze.entity.Product;
import kamikaze.support.HttpMethod;
import kamikaze.support.Service;
import kamikaze.support.ServiceConfig;
import kamikaze.support.ServiceContext;
import kamikaze.support.ServiceException;
import kamikaze.support.UserSession.Type;

@ServiceConfig(path = "product.delete.action", method = HttpMethod.GET)
public class DeleteProductService implements Service {

	@Override
	public String serve(ServiceContext ctx) throws Exception {
		final String id = ctx.getRequest().getParameter("id");
		if (id != null && !id.isEmpty()) {

			Query q = null;
			if (ctx.getUserSession().getType() == Type.User) {
				q = ctx
						.getEntityManager()
						.createQuery(
								"Select p from Product p where p.productId= :productId and deleted=false and ownerKey= :ownerKey");
				q.setParameter("productId", Long.valueOf(id));
				q.setParameter("ownerKey",ctx.getUserSession().asUser().getId());
				Product product = (Product) q.getSingleResult();
				product.setDeleted(true);
				
				ctx.getEntityManager().persist(product);
			} else if (ctx.getUserSession().getType() == Type.Admin) {
				q = ctx
						.getEntityManager()
						.createQuery(
								"Select p from Product p where p.productId= :productId and deleted=false");
				q.setParameter("productId", Long.valueOf(id));
				Product product = (Product) q.getSingleResult();
				product.setDeleted(true);
				
				ctx.getEntityManager().persist(product);
			} else {
				throw new ServiceException("User not Login");
			}
			
			return "redirect:/service/product/list";
		} else {
			throw new ServiceException("Product ID is unknown.");
		}
	}

}
